package com.kehongborui.spring.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhang peng yang ming
 * @create 2018-08-11 0:26
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    //空指针异常
    @ExceptionHandler(NullPointerException.class)
    public Map nullPointerExceptionHandler(NullPointerException ex) {
        return resultFormat(2, ex);
    }

    //自定义异常
    @ExceptionHandler(SpringException.class)
    public Map runtimeExceptionHandler(SpringException ex) {
        return resultFormat(-1001, ex);
    }

    private <T extends Throwable> Map resultFormat(Integer code, T ex) {
        ex.printStackTrace();
        Map<String, Object> err = new HashMap<>();
        err.put("code", code);
        err.put("msg", ex.getMessage());
        return err;
    }
}
